package cn.lcj.basic.interceptor;

import cn.lcj.basic.jwt.JwtUtils;
import cn.lcj.basic.jwt.LoginData;
import cn.lcj.basic.jwt.RsaUtils;
import io.jsonwebtoken.ExpiredJwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.PublicKey;
import java.util.concurrent.TimeUnit;

/**
 * $
 *
 * @return $
 * @date $ $
 * @description $
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求头里获取token
        String token = request.getHeader("token");
        //判断token是否为null 当没登录token为null是 会报non null key requird错误
        if(token!=null){
            try {
                //获取公钥
                PublicKey publicKey = RsaUtils.getPublicKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pub").getFile());
                //解密
                JwtUtils.getInfoFromToken(token, publicKey, LoginData.class);
                return true;//没有刷新时间
            } catch (ExpiredJwtException e) {
                e.printStackTrace();
                //跳转到登录页面,响应json数据给前端，让前端跳转，告诉前端这是个json格式
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().println("{\"success\":false,\"msg\":\"timeout\"}");//不走controller
                return false;
            }
        }

        //跳转到登录页面,响应json数据给前端，让前端跳转，告诉前端这是个json格式
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println("{\"success\":false,\"msg\":\"noLogin\"}");
        //{success:false,"message":"noLogin"}
        return false;
    }
}
